<template>
  <div class="groupSendContainer autpGrow flex-column">
    <div class="filterCondation">
      <div class="filterTitle">
        筛选条件
      </div>
      <div class="layui-input-inline flex-row condations layui-form">
        <span class="label">发送内容</span>
        <input type="text" class="layui-input" v-model="filterText">
        <span class="label">类型</span>
        <div class="layui-input-block">
          <select name="city" placeholder="默认" lay-filter="changeType" ref="typeSelect">
            <option value=""></option>
            <option
              :value="type.value"
              v-for="(type, i) in types"
              :key="i"
              >{{type.label}}</option>
          </select>
        </div>
        <span class="label">状态</span>
        <div class="layui-input-block">
        <select name="city" placeholder="默认" lay-filter="changeStatus" ref="statusSelect">
          <option value=""></option>
          <option
            :value="status.value"
            v-for="(status, i) in statusEnum"
            :key="i"
            >{{status.label}}</option>
        </select>
        </div>
        <span class="label">时间</span>
        <input class="layui-input" autocomplete="off" id="startTime" v-model="startTime">
        <div class="layui-form-mid">-</div>
        <input class="layui-input" autocomplete="off" id="endTime" v-model="endTime">
        <!-- <button class="layui-btn" type="reset" @click="resetCondation">清除条件</button> -->
      </div>
    </div>
    <div class="historyContent flex-row autoGrow">
      <div class="list historyList flex-column autoGrow infinite-list" v-infinite-scroll="load">
        <div :class="{'historyItem list-item':true,'actived':currentRecord&&currentRecord.id === item.id }"
          @click="changeCurrentRecord(item)"
          v-for="(item, i) in filterRecords"
          :key="item.id">
          <div class="topInfo flex-row">
            <div>
              <img
              v-for="(s, index) in item.services.slice(0,2)"
              :src="s&&s.avatar"
              :key="index"
              alt="">
            </div>
            <div class="ignoreMore" v-if="item.services.length >= 2"></div>
            <el-tag type="warning" size="medium" v-if="item.content[0].msgtype === 13">
              {{ item.content[0].wxid.indexOf('gh_')===0?'公众号':'好友名片' }}
            </el-tag>
            <el-tag type="warning" size="medium" v-else>
              {{ WechatMessageType[item.content[0].msgtype||0].text }}
            </el-tag>
            <div class="send-content autoGrow textEllipsis" v-if="item.content[0].msgtype === 13">
              {{item.content[0].title}}
            </div>
             <div class="send-content autoGrow textEllipsis" v-if="item.content[0].msgtype === 16">
              From：{{item.content[0].forwardWxid}} ID: {{item.content[0].forwardMsgId}}
            </div>
            <div class="send-content autoGrow textEllipsis" v-else>
              {{item.content[0].content||item.content[0].src}}
            </div>
            
            <el-button disabled="" size="small">{{flagMap[item.status]}}</el-button>
            <el-button type="danger"  size="small"
              v-if="item.status == 'complete'"
              @click.stop="deleteRecord(item, i)" >
              删除
            </el-button>
            <el-button size="small" type="warning" v-else  @click.stop="cancelSend(item, i)">取消发送</el-button>
          </div>
          <div class="bottomInfo flex-row fontGrey">
            <div class="sendTime">
              {{ item.createtime }}
            </div>
            <!-- <div class="sendCount">发送{{item.count}}个{{flagMap[item.type]}}</div> -->
            <div class="sendFriendCount">发送{{item.count}}个{{!!item.msgtype===false?'好友':'群'}}</div>
            <div class="taskType autoGrow flex-row">
              <span>{{item.sendtime ? `定时发送 ${ item.sendtime }` : '即时群发'}}</span>
              <span v-if="item.status=='sending'">{{item.successCount}}/{{item.totalCount}}</span>
            </div>
            
          </div>
        </div>
      </div>
      <div class="historyDetail flex-column autpGrow">
      <slot v-if="currentRecord">
        <el-card class="box-card info-card">
          <div slot="header" class="clearfix">
              <span>消息</span>
          </div> 
          <div class="quick-item" v-for="(content, index) in currentRecord.content" :key="index">
              <messageCard :message="content" />
          </div>
          
          <el-divider v-if="currentRecord.status==='waiting'"></el-divider>
          <div style="text-align:right" v-if="currentRecord.status==='waiting'">
            <el-button size="small" type="primary" @click="edit(currentRecord)">再次编辑</el-button>
          </div>
        </el-card>
        <el-card class="box-card sender-card">
          <div slot="header" class="sender-card-header">
            <span>发送账号  ({{currentRecord.services.length}}个)</span>
            <el-button v-if="currentRecord.services.length>2" size="small" type="text" class="click-span" @click="()=>this.showAllServices=!this.showAllServices">
            {{showAllServices ? '收起' : '详细'}}
            </el-button>
          </div>
          <el-row class="clearfix">
            <div class="sender-card-grid" v-if="currentRecord.services[0]">
            <div class="sender-card-item" :key="item.id" v-for="(item) in !showAllServices ? currentRecord.services.slice(0,2) : currentRecord.services">
              <friend 
                :avatar="item.avatar"
                :name="item.nick"
                :wxid="item.wxid"
                :gender="item.gender"
                class="sender-card-friend"
              />
            </div>
            </div>
          </el-row>
        </el-card>
        <el-tabs class="box-card receiver-card" type="border-card" v-model="objectTab">
          <el-tab-pane label="发送成功" name="0">
            <template v-for="(item) in successReceivers">
              <div :key="item.id">
                <friend
                  v-if="item.friendwxid.indexOf('@chatroom')<0"
                  :avatar="item.avatar" 
                  :name="item.friendnick"  
                  :wxid="item.friendwxid"
                  :gender="item.gender"
                  class="send-receiver"
                />  
                <group
                  v-else
                  :avatar="item.avatar" 
                  :name="item.friendnick"  
                  :member="item.personnum"
                  :friend="item.friendNum"
                  class="send-receiver"
                />
              </div>
            </template>
            <div class="empty" v-if="!successReceivers.length">
              暂无数据
            </div> 
          </el-tab-pane>
          <el-tab-pane label="待发送" name="-100">
            <template v-for="(item) in sendingReceivers">
              <div :key="item.id">
                <friend
                  v-if="item.friendwxid.indexOf('@chatroom')<0"
                  :avatar="item.avatar" 
                  :name="item.friendnick"  
                  :wxid="item.friendwxid"
                  :gender="item.gender"
                  class="send-receiver"
                />  
                <group
                  v-else
                  :avatar="item.avatar" 
                  :name="item.friendnick"  
                  :member="item.personnum"
                  :friend="item.friendNum"
                  class="send-receiver"
                />
              </div>
            </template>
            <div class="empty" v-if="!sendingReceivers.length">
              暂无数据
            </div> 
          </el-tab-pane>
          <el-tab-pane label="发送失败" name="-1">
            <template v-for="(item) in failReceivers">
              <div class="send-receiver-fail" :key="item.id">
                <friend
                  v-if="item.friendwxid.indexOf('@chatroom')<0"
                  :avatar="item.avatar" 
                  :name="item.friendnick"  
                  :wxid="item.friendwxid"
                  :gender="item.gender"
                  class="send-receiver"
                />  
                <group
                  v-else
                  :avatar="item.avatar" 
                  :name="item.friendnick"  
                  :member="item.personnum"
                  :friend="item.friendNum"
                  class="send-receiver"
                />
                <span class="msg">{{WechatCode[item.rststatus]}}</span>
              </div>
            </template>
            <div class="empty" v-if="!failReceivers.length">
              暂无数据
            </div>
          </el-tab-pane>
          
          
        </el-tabs>
      </slot>
      </div>
    </div>
  </div>
</template>
<script>
import {mapState} from 'vuex'
import SendContent from '@/components/sendContent.vue'
import ServiceListItem from '@/components/serviceListItem.vue'
import UserListItem from '@/components/userListItem.vue'
import WechatMessageType from '@/lib/wechat-message-type'
import WechatCode from '@/lib/wechat-code'
import Message from '@/components/message'
import pinyin from '@/lib/pinyin'
import messageCard from '@/components/message-card'
import friend from '@/components/friend'
import group from '@/components/group'

export default {
  name: 'groupSendHistory',
  data() {
    return {
      startTime: '',
      endTime: '',
      filterText: '',
      filterType:'',
      filterStatus:'',
      objectTab: '0',
      WechatMessageType,
      WechatCode,
      flagMap: {
        waiting: '未发送',
        ongoing: '进行中',
        complete: '完成',
        error: '失败',
        text: '文本',
        image: '图片',
        link: '链接',
        notice: '群公告',
        contactAccount: '个人名片',
        officialAccount: '公众号名片'
      },
      types: [
        {
          value: '1',
          label: '文本'
        },
        {
          value: '6',
          label: '文件'
        },{
          value: '2',
          label: '图片'
        }
        ,{
          value: '13',
          label: '名片'
        },{
          value: '14', // 临时分类 名片 和 公众号是同一种
          label: '公众号'
        },{
          value: '10',
          label: '链接'
        },{
          value: '15',
          label: '群公告'
        },{
          value: '16',
          label: '转发'
        }

      ],
      statusEnum: [
        {
          value: 'waiting',
          label: '等待中',
        },{
          value: 'ongoing',
          label: '发送中',
        },{
          value: 'complete',
          label: '完成',
        },{
          value: 'error',
          label: '发送失败',
        }
      ],
      sendRecords: [],
      showAllServices: false,
      currentRecord: null,
      
      pageSize:10,
      pageNo:0,
      fetching:false
    }
  },
  mounted() {
    const that = this;
    layui.form.render();
    layui.form.on('select(changeType)', this.changeFilterType)
    layui.form.on('select(changeStatus)', this.changeFilterStatus)
    layui.laydate.render({
      elem: '#startTime',
      trigger: 'click',
      type: 'datetime',
      lang: 'cn',
      // min: 0,
      done(val) {
        that.startTime = val
      }
    });
    layui.laydate.render({
      elem: '#endTime',
      trigger: 'click',
      type: 'datetime',
      lang: 'cn',
      min: that.startTime,
      done(val) {
        that.endTime = val
      }
    });
    //this.initRecords()
  },
  components: {
    SendContent,
    ServiceListItem,
    UserListItem,
    Message,
    messageCard,
    friend,
    group
  },
  watch:{
    currentRecord(val,oldVal){
      oldVal = oldVal ||{}
      if(val && val.id !== oldVal.id ){
        this.showAllServices = false    
      }
    }
  },
  methods: {
    changeFilterType({value}) {
      this.filterType = value
    },
    changeFilterStatus({value}) {
      this.filterStatus = value
    },
    getServicesByWxids(msgextra){
      const accounts = this.accountWxidMap
      const services = (msgextra||'').split(',').map(wxid=>accounts[wxid])
      return services
    },
    getServiceByWxid(wxid){
      const accounts = this.accountMap
      return accounts.filter(account=>account.wxid === wxid)[0] 
    },
    load(){
      console.log('load')
      this.initRecords()
    },
    initRecords() {
      const types = {
        1: 'text',
        2: 'image',
        3: 'emoji',
        4: 'video',
        5: 'audio',
        6: 'documents',
        10: 'link',
        13: 'contact',
        15: 'notice',
        16: 'forward'
      }
      const statuses = {
        0: 'complete',
        1: 'ongoing',
        2: 'waiting',
        3:  'error'
      }
      const adminid = this.uistate.adminid
      if(this.fetching)return;
      this.fetching = true
      this.$api.groupSend.list({
        csId: this.manager.id,
        pageSize:this.pageSize,
        pageNo:this.pageNo+1
      }).then(data=>{
        this.fetching = false
        this.pageNo = this.pageNo+1
        const _sendRecords =  data.map(item=>{
          let content
          try {
            content = JSON.parse(item.msgcontent)
          } catch (error) {
            content = { content:item.msgcontent,msgtype:1 }
          }
          if(!(content instanceof Array)){
            content = [content]
          }
          const { taskcount, sentcount,failcount } = item
          let sendstate = ''
          if( failcount){
            sendstate = statuses[3] 
          }else if( sentcount==0 ){
            sendstate = statuses[2]
          }else if(taskcount == sentcount){
            sendstate = statuses[0]
          }else if(taskcount != sentcount){
            sendstate = statuses[1]
          }
          return {
            ...item,
            type: types[item.msgtype]||'text',
            content,
            services:this.getServicesByWxids(item.msgextra),
            status: sendstate,
            count: item.taskcount,
            receivers: this.transUserData([]),
            sendtime: item.sendtime && this.formatTime(item.sendtime),
            createtime: this.formatTime(item.createtime || item.updatetime||0),
            successCount: item.sentcount,
            totalCount: item.taskcount,
          }
        })
        if(this.pageNo === 1){
          this.sendRecords = _sendRecords
          this.changeCurrentRecord(this.sendRecords[0])
        }else{
          this.sendRecords = this.sendRecords.concat(_sendRecords)
        }
        
      }).catch(e=>{
        this.fetching = false
        console.log(e)
      })
    },
    resetCondation() {
      this.filterText = ''
      this.filterType = ''
      this.filterStatus = ''
      this.$refs.typeSelect.value = ''
      this.$refs.statusSelect.value = ''
      this.startTime = ''
      this.endTime = ''
      layui.form.render('select')
    },
    changeCurrentRecord(record) {
      this.$api.groupSend.listTaskDetail({ taskId:record.id})
        .then(rs=>{
          if(rs){
            const { items ,groups,friends } = rs;
            const { toaccount } = items;

            const list = items.map(item=>{
              const toaccount = item.toaccount||''
              let _info
              if(toaccount.endsWith('@chatroom')){
                _info = groups.filter(group=>group.groupno === toaccount)[0]||{}
              }else{
                _info = friends.filter(friend=>friend.friendwxid === toaccount)[0]||{}
              }
              return {...item, 
                avatar: _info.avatar,
                friendwxid:_info.groupno||_info.friendalias||_info.friendwxid||'',
                friendnick:_info.groupname||_info.friendnick,
                id:_info.id,
                personnum:_info.personnum,
                friendNum:_info.friendNum

                }
            })
            this.currentRecord.receivers = list
            console.log(this.currentRecord)
          }
          
          
        })
        .catch(e=>{
          console.log(e)
        })
      this.currentRecord = record;
      this.changeObjectTab(0)
    },
    changeObjectTab(tab) {
      // this.objectTab = tab;
    },
    deleteRecord(record, index) {
      this.$api.groupSend.delete({
        taskId: record.id
      }).then(()=>{
        console.log(record)
        this.sendRecords = this.sendRecords.filter(item=>item.id!=record.id)
      }).catch(e=>this.$msg(e))
    },
    cancelSend(record, index) {
      this.$api.groupSend.delete({
        taskId: record.id
      }).then(()=>{
        this.sendRecords = this.sendRecords.filter(item=>item.id!=record.id)
      }).catch(e=>this.$msg(e))
    },
    edit(record) {
      this.$router.push({
        name: 'NewGroupSend',
        params: record
      })
    }
  },
  computed: {
    ...mapState(['manager', 'services','accountMap','uistate']),
    accountWxidMap(){
      const map={}
      Object.values(this.accountMap)
        .forEach(item=>{
          map[item.wxid] = item
        }) 
      return map  
    },
    tabContentList() {
      return this.currentRecord.receivers.filter(s=>s.rststatus == 0);
    },
    successReceivers(){
      return this.currentRecord.receivers.filter(s=>s.rststatus == 0);
    },
    sendingReceivers(){
      return this.currentRecord.receivers.filter(s=>s.rststatus == -999||s.rststatus == -100);
    },
    failReceivers(){
      return this.currentRecord.receivers.filter(s=>s.rststatus !== 0&&s.rststatus !== -100&&s.rststatus !== -999);
    },
    filterRecords(){
      const filterText = pinyin.getFullChars(this.filterText).toLocaleLowerCase() ;
      const filterType = +this.filterType
      const filterStatus = this.filterStatus
      const startTime = this.startTime?+new Date(this.startTime):0
      const endTime = this.endTime?+new Date(this.endTime):0
      return this.sendRecords.filter(item=>{
        const chars = pinyin.getFullChars(item.msgcontent).toLocaleLowerCase();
        const createTime = +new Date(item.createtime)
        if(chars.indexOf(filterText)<0 )return false
        if( filterType){
          if( filterType === 14 ){
            if(!item.content.filter(i=>i.certflag).length)return false
          }else{
            if(!item.content.filter(i=>i.msgtype===filterType).length)return false
          }
        }
        if( filterStatus!=='' && filterStatus!==item.status  )return false

        if( startTime && endTime   ){
          if( startTime > createTime || endTime < createTime )return false
        } 

        return chars.indexOf(filterText)>-1 
      })
    }
  }
}
</script>
<style scoped>
.groupSendContainer .historyContent{
  height: 100%;
}
.groupSendContainer .historyList{
  height: 100%;
}
.groupSendContainer .historyList .historyItem{
  height: auto;
}
.groupSendContainer .historyList .historyItem .layui-badge{
  margin: 0 12px;
  padding: 0 20px;
  width: auto;
}
.groupSendContainer .historyList .historyItem.actived{
  background: #eee
}
.groupSendContainer .historyList .historyItem .topInfo{
  height: auto;
  width: 100%;
}
.groupSendContainer .historyList .historyItem .bottomInfo{
  line-height: 32px;
}
.groupSendContainer .historyList .sendTime{
  margin-right: 20px;
}
.groupSendContainer .condations input{
  width: 160px;
}
.send-content{
  margin-left: 10px; 
}
.list{
  display: flex;
  flex-direction: column;
  padding: 0 10px;
  background: #fafafa;
}
.list-item{
  padding: 10px 16px;
  background-color: #fff;
  border-radius: 4px;
  border-left: 5px solid #50bfff;
  margin: 5px 0;  
  cursor: pointer; 
  box-shadow: 0px 1px 1px 1px #ddd;
  transition:transform 200ms;
  padding-right: 10px; 
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
  height:auto
}
.list-item:hover{
  transform:translateX(-10px) 
}
.click-span{
  /* float:right; */
}
.box-card{
  margin: 10px 10px 0 10px;
}
.info-card{
  flex-shrink: 0; 
}
.sender-card{
  flex-shrink: 0; 
}
.sender-card-header{
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content:space-between;
  flex-shrink: 0;
}
.sender-card-header .el-button{
  padding: 0
}
.sender-card-grid{
  margin-right: -10px;
  margin-top: -10px;
}
.sender-card-item{
  padding-right: 10px;
  padding-top: 10px;
  width: 50%;
  box-sizing: border-box;
  float: left;
}

.sender-card-friend{

}
.send-receiver{
  margin: 5px 0;
}
.send-receiver-fail{
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}
.send-receiver-fail .msg{
  font-size: 12px;
  color: #666
}
.receiver-card .empty{
  font-size: 14px;
  color: #666
}
.quick-item{
    padding: 10px 16px;
    background-color: #fff;
    border-radius: 4px;
    border-left: 5px solid #50bfff;
    margin: 5px 0;  
    cursor: pointer; 
    box-shadow: 0px 1px 1px 1px #ddd;
    transition:transform 200ms;
    padding-right: 10px;
}

</style>
